<template>
  <view class="payment-container">
    <view class="merchant-info">
      <image class="merchant-avatar" :src="imgurl + formData.merAvatar" alt=""> </image>
      <text class="merchant-name font-bold">{{ formData.merName }}</text>
    </view>
    <view class="payment-input" @tap="openkeyboard">
      <text class="font-large">￥</text>
      <input class="input-field font-large" v-model="payPrice" type="number" placeholder="输入付款金额" @focus="openkeyboard" readonly disabled />
      <cu-keyboard ref="cukeyboard" @change="changeKeybord" @confirm="handleClose"></cu-keyboard>
    </view>

    <view class="remark-input">
      <input class="input-field" v-model="mark" placeholder="备注" @focus="closeKeyboard()" />
    </view>
    <view class="discount-details" v-if="payPrice">
      <view class="discount-item" v-if="userInfo.isComunityVip != 1">
        <text class="discount-title">消费补贴返还</text>
        <text class="discount-value">{{ integralGive || 0 }}</text>
      </view>
      <view class="discount-item" v-if="userInfo.isComunityVip == 1">
        <text class="discount-title">折扣方式</text>
        <text class="discount-value">{{ discountData.typeName || 0 }}</text>
      </view>

      <view class="discount-item">
        <text class="discount-title">平台积分余额</text>
        <text class="discount-value">{{ jifen || 0 }}</text>
      </view>
      <view class="discount-item">
        <text class="discount-title">使用平台积分</text>
        <text class="discount-value">{{ userInfo.isComunityVip == 1 ? formData.comunityIntegralUse : 0 }}</text>
      </view>
      <view class="discount-item">
        <text class="discount-title">抵扣金额</text>
        <text class="discount-value">￥{{ userInfo.isComunityVip == 1 ? formData.comunityIntegralDeduction : 0 }}</text>
      </view>
      <view class="discount-item">
        <text class="discount-title">付款方式</text>
        <text class="discount-value" @click="onShow = true">{{ getPayTypeName(orderType) }}</text>
      </view>
      <view class="total-amount">
        <text class="total-label">小计</text>
        <text class="total-value font-large">￥{{ userInfo.isComunityVip == 1 ? (payPrice - formData.comunityIntegralDeduction).toFixed(2) : payPrice }}</text>
      </view>
    </view>
    <discount ref="discount" :formData="formData" @getInfo="getInfo" />
    <!-- <change-address ref="changeAddress" :type="2" :lists="formData.frontComunityInteralPoVoList" @getAddress="getAddress" /> -->
    <u-popup v-model="onShow" mode="bottom" round>
      <view class="payment-popup">
        <!-- <payment ref="payment" @onChange="onChange"></payment> -->
      </view>
    </u-popup>
  </view>
</template>

<script>
import { getUserInfo, programlogin } from "../../../utils/request_api.js"; /* 登录界面挪动接口 */
import cukeyboard from "../../../components/cu-keyboard/cu-keyboard.vue";
import discount from "./discount.vue";
// import changeAddress from "./components/address.vue";
// import payment from "@/components/payments/index.vue";
// import { mapGetters } from "vuex";
import { getMerInfoByid, fastPaymentDiscountMethod, fastPayment } from "../../../utils/api/local";
// import getOrderPay from "@/mixins/getOrderPay.js";
import { IMG_URL } from "../../../config/index";
export default {
  //   mixins: [getOrderPay],
  components: {
    cukeyboard,
    discount,
    // changeAddress,
    // payment,
    // "number-keyboard": () => import("@/components/number-keyboard.vue"), // 假设你有一个自定义的数字键盘组件
    // "u-icon": () => import("uview-ui/components/u-icon/u-icon.vue"),
    // "u-popup": () => import("uview-ui/components/u-popup/u-popup.vue"),
  },
  //   computed: mapGetters(["userInfo"]),
  watch: {
    payPrice: {
      handler(val) {
        /**
         * 计算消费补贴抵扣
         * 1.10补贴固定抵扣1块钱（后期会改）
         * 2.若补贴充足，按金额计算最大可抵扣金额
         * 3.若补贴不足，按最大可使用补贴计算 */
        /** 消费补贴可抵扣最大金额:根据输入金额计算 */
        let integral = Number(this.userInfo.integral || 0);
        if (Number(this.formData.xiaofeiDikouWuyejiaofeiBili || 0)) {
          let maxPrice = val * (this.formData.xiaofeiMaxUseBili || 0);
          /** 所有补贴可抵扣金额:根据当前补贴计算 */
          let integraPrice = integral * this.formData.xiaofeiDikouWuyejiaofeiBili;
          /** 若输入金额的最大抵扣金额超出账户补贴所能抵扣金额，则按最大只能抵扣所有补贴可抵扣金额 */
          if (maxPrice > integraPrice) {
            this.formData.consumeIntegralUse = integral.toFixed(2);
            this.formData.consumeIntegralDeduction = integraPrice.toFixed(2);
          } else {
            /** 若输入金额最大可抵扣金额小于账户补贴能抵扣金额，则按最大所能抵扣金额计算 */
            this.formData.consumeIntegralUse = (maxPrice / this.formData.xiaofeiDikouWuyejiaofeiBili).toFixed(2);
            this.formData.consumeIntegralDeduction = maxPrice.toFixed(2);
          }
        } else {
          this.formData.comunityIntegralUse = 0.0;
          this.formData.comunityIntegralDeduction = 0.0;
        }
        /**
         * 平台积分抵扣
         * 1.10补贴固定抵扣1块钱
         * 2.根据输入金额计算最大可抵扣金额
         * 3.根据抵扣金额计算需扣除补贴
         */
        let gpWyPaymentAmount = Number(this.userInfo.isComunityVip == 1 ? this.userInfo.gpWyPaymentAmount : 0);
        if (Number(this.formData.wuyeDikouwuyejiaofeiBili || 0)) {
          let maxComunityPrice = val * (this.formData.offlineIntegralProperty || 0);
          /** 当前补贴最大可抵扣金额 */
          let integraComunityPrice = gpWyPaymentAmount * this.formData.wuyeDikouwuyejiaofeiBili;
          if (maxComunityPrice > integraComunityPrice) {
            this.formData.comunityIntegralUse = gpWyPaymentAmount.toFixed(2);
            this.formData.comunityIntegralDeduction = integraComunityPrice.toFixed(2);
          } else {
            this.formData.comunityIntegralUse = (maxComunityPrice / this.formData.wuyeDikouwuyejiaofeiBili).toFixed(2);
            this.formData.comunityIntegralDeduction = maxComunityPrice.toFixed(2);
          }
        } else {
          this.formData.comunityIntegralUse = 0;
          this.formData.comunityIntegralDeduction = 0.0;
        }
        console.log(this.formData);
        // this.formData.comunityIntegralUse = Math.round(maxComunityPrice * 10);
        // this.formData.comunityIntegralDeduction = maxComunityPrice.toFixed(2);
        /** 计算总金额 */
        let price = Number(this.discountData.price || 0);
        this.allPrice = (val - price).toFixed(2);
        if (this.formData.isOfflineIntegralProportionBack == 1) {
          /** 计算返还补贴 */
          let integral = val * (this.formData.offlineIntegralProportionBack || 0);
          this.integralGive = integral.toFixed(2);
        }
        this.$refs.discount.getInfo(this.discountData.type);
      },
    },
  },
  data() {
    return {
      imgurl: IMG_URL,
      jifen: 0,
      onShow: false,
      mark: "",
      loading: false,
      integralGive: 0,
      allPrice: 0,
      showKeyboard: false,
      payPrice: "",
      discountData: {
        type: 0,
        typeName: "无抵扣",
      },
      userInfo: "",
      formData: {
        name: "",
      },
      ebMerId: "",
      orderType: "pay_ls",
    };
  },
  onShow() {
    this.userInfo = uni.getStorageSync("userInfo");
  },
  onLoad(option) {
    this.openkeyboard();
    if (option.id) {
      this.ebMerId = option.id;
      this.userType = 1;
    } else {
      const q = decodeURIComponent(option.q); // 获取到二维码原始链接内容
      console.log(q);
      this.ebMerId = q.split("/")[q.split("/").length - 1].split("-")[0];
      this.userType = q.split("/")[q.split("/").length - 1].split("-")[1];
      console.log(this.ebMerId);
      const scancode_time = parseInt(option.scancode_time); // 获取
    }
    this.getMerInfoByid(this.ebMerId);
    this.$nextTick(() => {
      this.handleClose();
    });
  },
  methods: {
    /* 登录界面挪动接口结束 */
    closeKeyboard() {
      this.$refs.cukeyboard.close();
    },
    changeKeybord(aa) {
      this.payPrice = aa;
    },
    openkeyboard() {
      this.$refs.cukeyboard.open();
    },
    getPayTypeName(type) {
      switch (type) {
        case "pay_weixin":
          return "微信支付";
        case "pay_yue":
          return "余额支付";
        case "pay_ls":
          return "快捷支付";
      }
    },
    onInput(key) {
      const regex = /^(\d+)(\.\d{0,2})?$/;
      if (!regex.test(this.payPrice + key)) return;
      this.payPrice += key;
    },
    onDelete() {
      this.payPrice = "";
    },
    showloginJs() {
      let that = this;
      uni.login({
        provider: "weixin",
        success: (res) => {
          if (res.code) {
            that.autoLogin(res.code);
          } else {
            console.error("登录失败:", res.errMsg);
            uni.showToast({
              title: "微信登录失败，请稍后再试",
              icon: "none",
            });
          }
        },
        fail: (err) => {
          console.error("登录失败:", err);
          uni.showToast({
            title: "微信登录失败，请稍后再试",
            icon: "none",
          });
        },
      });
    },
    /* 免登录-每个界面调用 */
    async autoLogin(code) {
      let that = this;
      wx.getUserInfo({
        success(res) {
          const { nickName, avatarUrl, gender } = res.userInfo;
          programlogin({ code, avatar: avatarUrl, nickName, sex: gender }).then((response) => {
            const data = response.data;
            console.log("🚀 ~ programlogin ~ data:", data);
            that.authKey = data.key;
            if (data.type === "login") {
              uni.setStorageSync("uid", data.uid);
              uni.setStorageSync("token", data.token);
              uni.setStorageSync("userInfo_data", data);
              uni.setStorageSync("openID", data.key);
              that.fastPaymentDiscountMethods(that.ebMerId);
            } else {
              console.log("@@@@@@@@@@@@@@@-88888888888888");
              uni.showModal({
                title: "提示",
                content: "您的登录已过期或未登录，请重新登录。",
                success: (res) => {
                  if (res.confirm) {
                    uni.clearStorage();
                    uni.setStorageSync("ebMerId", this.ebMerId);
                    uni.setStorageSync("userType", this.userType);
                    uni.switchTab({
                      url: "/pages_h5/myCenter/index?merId=" + this.ebMerId, // 假设登录页面的路径为 /pages_h5/login/index
                    });
                  }
                },
              });
            }
          });
        },
        fail: () => {
          uni.showToast({
            title: "您需要授权，才能获取您的信息！",
          });
        },
      });
    },
    async handleClose() {
      var e = await getUserInfo();
      if (e.code == 401) {
        this.showloginJs(); // uni.showModal({
        //   title: "提示",
        //   content: "您的登录已过期或未登录，请重新登录。",
        //   success: (res) => {
        //     if (res.confirm) {
        //       uni.clearStorage();
        //       uni.setStorageSync("ebMerId", this.ebMerId);
        //       uni.setStorageSync("userType", this.userType);
        //       uni.switchTab({
        //         url: "/pages_h5/myCenter/index?merId=" + this.ebMerId, // 假设登录页面的路径为 /pages_h5/login/index
        //       });
        //     }
        //   },
        // });
        // return;
      } else {
        this.fastPaymentDiscountMethods(this.ebMerId);
      }
      if (!this.payPrice) {
        uni.showToast({
          title: "请输入具体金额",
          icon: "none",
        });
        return false;
      }
      if (this.payPrice <= 0) {
        uni.showToast({
          title: "请输入大于0的金额",
          icon: "none",
        });
        return false;
      }
      if (this.payPrice >= 50000) {
        uni.showToast({
          title: "金额过大",
          icon: "none",
        });
        return false;
      }
      if (this.orderType === "pay_yue" && Number(this.userInfo.nowMoney || 0) < this.allPrice) {
        uni.showToast({
          title: "请先充值",
          icon: "none",
        });
        return false;
      }
      this.loading = true;
      let params = {
        gainIntegral: this.userInfo.isComunityVip != 1 ? this.integralGive : 0,
        comunityIntegral: this.discountData.type == 2 && this.userInfo.isComunityVip == 1 ? this.formData.comunityIntegralUse : 0,
        useIntegral: this.discountData.type === 1 ? this.discountData.discount : 0,
        deductionPrice: this.formData.comunityIntegralDeduction,
        discountType: this.discountData.type,
        ebComunityHouseId: this.discountData.ebComunityHouseId,
        ebComunityHouseName: this.discountData.address,
        ebMerId: this.ebMerId,
        ebMerName: this.formData.merName,
        mark: this.mark,
        payPrice: this.allPrice,
        uid: uni.getStorageSync("uid"),
        totalPrice: this.payPrice,
        payType: "lszfxcx",
        // payType: this.getPayType(this.orderType),
      };
      fastPayment(params)
        .then((obj) => {
          let leshua = obj.data.leshuaPayRequest.leshua_order_id;
          uni.requestPayment({
            timeStamp: obj.data.jsConfig.timeStamp, //后端返回的时间戳
            nonceStr: obj.data.jsConfig.nonceStr, //后端返回的随机字符串
            package: obj.data.jsConfig.packages, //后端返回的prepay_id
            signType: "RSA", //后端签名算法,根据后端来,后端MD5这里即为MD5
            paySign: obj.data.jsConfig.paySign, //后端返回的签名
            payCompletedPageOptions: {
              showNavBackButton: true,
            },
            success(res) {
              console.log("用户支付扣款成功", res);
              res.payCompletedPage.onUnload((dawd) => {
                console.log(dawd);
                uni.switchTab({
                  url: "/pages_h5/index/index", // 点击左上角返回按钮，会触发支付回调页onUnload 事件，在 onUnload 事件触发时可以跳转到别的页面
                });
              });
              // uni.request({
              //   url: "https://www.wantongkonggu.cn/api/frontApph7/order/get/pay/lsReceipt",
              //   method: "GET",
              //   data: { leshuaOrderId: leshua },
              //   success: (resd) => {
              //     uni.request({
              //       url: "https://www.wantongkonggu.cn/api/frontApph7/pay/LsQueryPayResult",
              //       method: "GET",
              //       data: { orderNo: resd.data.data.orderId },
              //       success(ressss) { },
              //     });
              //   },
              //   fail: (err) => {
              //     that.errdata = JSON.stringify(err);
              //   },
              //   complete: (ress) => { },
              // });
            },
            fail(res) {
              console.log("用户支付扣款失败", res);
            },
          });
        })
        .catch((err) => {
          this.loading = false;
          uni.showToast({
            title: "商户资料审核中，暂未开通支付",
            icon: "none",
          });
        });
    },
    onDiscount() {
      this.$refs.discount.handleOpen();
    },
    handleOpenAddress() {
      this.$refs.changeAddress.handleOpen();
    },
    getInfo(data) {
      this.discountData = data;
      let price = Number(this.discountData.price || 0);
      // this.allPrice = (this.payPrice - price).toFixed(2);
      this.allPrice = (this.payPrice - this.formData.comunityIntegralDeduction).toFixed(2);
    },
    getAddress(data) {
      this.discountData.accumulationFund = data.accumulationFund || 0;
      this.discountData.ebComunityHouseId = data.ebComunityHouseId;
      this.discountData.address = data.address;
    },
    getMerInfoByid(id) {
      getMerInfoByid({ id }).then((res) => {
        this.formData = res.data.ebMer || {};
      });
    },
    fastPaymentDiscountMethods(id) {
      fastPaymentDiscountMethod({
        ebMerId: id,
        userId: uni.getStorageSync("uid"),
      }).then((res) => {
        this.jifen = res.data.frontComunityInteralPoVo.accumulationFund || 0;
        this.formData = {
          ...this.formData,
          ...res.data,
        };
        this.$nextTick(() => {
          let temp = this.formData.frontComunityInteralPoVo != null ? 2 : 0;
          if (temp === 2) {
            if (this.userInfo.isComunityVip != 1) {
              temp = 0;
            }
          }
          this.$refs.discount.getInfo(temp);
        });
      });
    },
  },
};
</script>

<style lang="less" scoped>
.payment-container {
  font-family: "PingFang SC";
  padding: 0 20rpx;

  .merchant-info {
    padding-top: 20rpx;
    display: flex;
    align-items: center;
    margin-bottom: 1rem;

    .merchant-avatar {
      width: 3rem;
      height: 3rem;
      border-radius: 10%;
      margin-right: 0.5rem;
    }

    .merchant-name {
      flex: 1;
      font-size: 0.9rem;
      font-weight: bold;
    }
  }

  .payment-input {
    background-color: #fff;
    border-radius: 10rpx;
    position: relative;
    padding: 0.8rem;
    display: flex;
    align-items: center;
    border-radius: 20rpx;

    .input-field {
      flex: 1;
      font-size: 1.8rem;
      padding-left: 0.5rem;
      border: none;
      outline: none;
      height: 50px;
    }

    .delete-icon {
      position: absolute;
      top: 50%;
      right: 0.8rem;
      transform: translateY(-50%);
      width: 24px;
      height: 24px;
    }
  }

  .remark-input {
    padding: 0.8rem;
    background-color: #fff;
    border-radius: 20rpx;
    margin: 20rpx 0;

    .input-field {
      width: 100%;
      padding: 0.5rem;
      border: none;
      outline: none;
    }
  }

  .discount-details {
    padding: 0.8rem;
    margin-top: 1rem;
    background-color: #fff;
    border-radius: 20rpx;

    .discount-item {
      display: flex;
      justify-content: space-between;
      margin-bottom: 0.8rem;

      &:last-child {
        margin-bottom: 0;
      }

      .discount-title {
        font-size: 0.8rem;
        color: rgba(0, 0, 0, 0.6);
      }

      .discount-value {
        font-size: 1rem;
        color: #000;
      }
    }

    .total-amount {
      display: flex;
      justify-content: flex-end;
      margin-top: 1rem;
      align-items: center;

      .total-label {
        font-size: 0.8rem;
        color: rgba(0, 0, 0, 0.6);
        margin-right: 0.5rem;
      }

      .total-value {
        font-size: 1.8rem;
        color: #ff9500;
      }
    }
  }

  .payment-popup {
    padding: 1rem;
  }
}
</style>
